//
//  HttpRequest.m
//  Xspcf
//
//  Created by 小小算盘 on 16/1/22.
//  Copyright © 2016年 小小算盘. All rights reserved.
//

#import "HttpRequest.h"
#import "AFNetworking.h"
@implementation HttpRequest
+(void)postLoginRequestCacheURLStr:(NSString *)urlStr withParameter:(NSDictionary *)dic HaveAccessID:(BOOL)aAccessID IsHTML:(BOOL)aHtml success:(SuccessBlock)success failure:(ErrorBlock)failure{}

+(void)postRequestCacheURLStr:(NSString *)urlStr withParameter:(NSString *)parameters HaveAccessID:(BOOL)aAccessID IsHTML:(BOOL)aHtml success:(SuccessBlock)success failure:(ErrorBlock)failure{
    
    
    NSMutableArray *paramArr = [NSMutableArray arrayWithArray:[parameters componentsSeparatedByString:@"&"]];
    NSArray* arraySorted = [paramArr sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    NSMutableString *params = [NSMutableString string];
    for (NSString *item in arraySorted) {
        [params appendString:@"&"];
        [params appendString:item];
    }
    [params deleteCharactersInRange:NSMakeRange(0, 1)];
    
    NSString *md5 = @"dsfdas213#@@$";
    NSString *des = @"12345678";
    if ([[Sun getUser:KLOGIN] intValue] == 1) {
        md5 = [Sun getUser:MD5];
        des = [Sun getUser:DES];
    }
    NSString *md5Str = [Utility md5:[NSString stringWithFormat:@"%@&%@",params, md5]];
    NSString *desStr = [Utility encryptStr:[NSString stringWithFormat:@"%@&sign=%@",params,md5Str] Key:des IV:nil];
    NSMutableDictionary *paramDic =[NSMutableDictionary dictionaryWithObjectsAndKeys:desStr,@"params", nil];
    if ([[Sun getUser:KLOGIN] intValue] == 1) {
        [paramDic setObject:[Sun getUser:ACCESSID] forKey:@"accessId"];
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    if (aHtml == YES) {
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",nil];
    }
    [manager POST:urlStr parameters:paramDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        if ([dic[@"code"] intValue]==0||[dic[@"code"] intValue]==50000||[dic[@"code"] intValue]==100009) {
            success(dic,dic[@"msg"]);
        }else{
            failure(dic,dic[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSString *str=[NSString stringWithFormat:@"%@",error];
        if([str rangeOfString:@"Code=-1009"].location !=NSNotFound)
        {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"系统提示" message:@"您的网络出问题了，请检查网络是否连接。连接网络后，请重启程序，否则可能影响您的体验！" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
            [alert show];
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"系统提示" message:@"您的网络出问题了，请检查网络是否连接。连接网络后，请重启程序，否则可能影响您的体验！" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertView addAction:cancle];
            
            
            
            return ;
        }
        
    }];
    

}
+(void)postRequestXieyiURLStr:(NSString *)urlStr withParameter:(NSString *)parameters HaveAccessID:(BOOL)aAccessID IsHTML:(BOOL)aHtml success:(void(^)(id))aBlock{
    
    NSMutableArray *paramArr = [NSMutableArray arrayWithArray:[parameters componentsSeparatedByString:@"&"]];
    NSArray* arraySorted = [paramArr sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    NSMutableString *params = [NSMutableString string];
    for (NSString *item in arraySorted) {
        [params appendString:@"&"];
        [params appendString:item];
    }
    [params deleteCharactersInRange:NSMakeRange(0, 1)];
    
    NSString *md5 = @"dsfdas213#@@$";
    NSString *des = @"12345678";
    if ([[Sun getUser:KLOGIN] intValue] == 1) {
        md5 = [Sun getUser:MD5];
        des = [Sun getUser:DES];
    }
    NSString *md5Str = [Utility md5:[NSString stringWithFormat:@"%@&%@",params, md5]];
    NSString *desStr = [Utility encryptStr:[NSString stringWithFormat:@"%@&sign=%@",params,md5Str] Key:des IV:nil];
    NSMutableDictionary *paramDic =[NSMutableDictionary dictionaryWithObjectsAndKeys:desStr,@"params", nil];
    if ([[Sun getUser:KLOGIN] intValue] == 1) {
        [paramDic setObject:[Sun getUser:ACCESSID] forKey:@"accessId"];
    }

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    if (aHtml == YES) {
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",nil];
    }

    [manager POST:urlStr parameters:paramDic progress:^(NSProgress * _Nonnull uploadProgress) {
    
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    aBlock(responseObject);
    
    
    
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSString *str=[NSString stringWithFormat:@"%@",error];
        if([str rangeOfString:@"Code=-1009"].location !=NSNotFound)
        {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"系统提示" message:@"您的网络出问题了，请检查网络是否连接。连接网络后，请重启程序，否则可能影响您的体验！" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
            [alert show];

            return ;
        }
    
    }];
}



+ (void)postURL:(NSString *)urlStr withParam:(id)dic success:(SuccessBlock)success failure:(ErrorBlock)failure{
    if (!dic){
        dic = @{};
    }
    NSMutableDictionary *mutableDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    //@"device":@"iOS"
    [mutableDic setObject:@"iOS" forKey:@"device"];
    NSString *str = [Sun stringFromDictionary:(NSDictionary *)mutableDic];
    NSMutableArray *paramArr = [NSMutableArray arrayWithArray:[str componentsSeparatedByString:@"&"]];
    NSArray* arraySorted = [paramArr sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    NSMutableString *params = [NSMutableString string];
    for (NSString *item in arraySorted) {
        [params appendString:@"&"];
        [params appendString:item];
    }
    [params deleteCharactersInRange:NSMakeRange(0, 1)];
    
    NSString *md5 = @"dsfdas213#@@$";
    NSString *des = @"12345678";
    if ([[Sun getUser:KLOGIN] intValue] == 1) {
        md5 = [Sun getUser:MD5];
        des = [Sun getUser:DES];
    }
    NSString *md5Str = [Utility md5:[NSString stringWithFormat:@"%@&%@",params, md5]];
    NSString *desStr = [Utility encryptStr:[NSString stringWithFormat:@"%@&sign=%@",params,md5Str] Key:des IV:nil];
    NSMutableDictionary *paramDic =[NSMutableDictionary dictionaryWithObjectsAndKeys:desStr,@"params", nil];
    if ([[Sun getUser:KLOGIN] intValue] == 1) {
        if ( [Sun getUser:ACCESSID] != nil){
        [paramDic setObject:[Sun getUser:ACCESSID] forKey:@"accessId"];
        }
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:urlStr parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        int code = [responseObject[@"code"] intValue];
        if (code == 0) {
            success(responseObject[@"data"],responseObject[@"msg"]);
        }else if(code < 0){
            failure(responseObject[@"msg"],code);
        }else {
            [[Sun shareSun]hideActivity];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [[Sun shareSun]hideActivity];
        NSLog(@"******%@******",error);
//        [[Sun shareSun]showMsg:@"网络连接失败，请更换网络或稍后再试"];
    }];
}

/**
 *  检查网络链接是否正常，其返回值决定是否调用数据库数据
 *
 *  @return
 */
+ (BOOL)requestBeforeCheckNetWork {
    struct sockaddr zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sa_len = sizeof(zeroAddress);
    zeroAddress.sa_family = AF_INET;
    SCNetworkReachabilityRef defaultRouteReachability =
    SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    BOOL didRetrieveFlags =
    SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    if (!didRetrieveFlags) {
        // printf("Error. Count not recover network reachability flags\n");
        return NO;
    }
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    BOOL isNetworkEnable  =(isReachable && !needsConnection) ? YES : NO;
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].networkActivityIndicatorVisible =isNetworkEnable;/*  网络指示器的状态： 有网络 ： 开  没有网络： 关  */
    });
    return isNetworkEnable;
}
@end
